#include <queue>
using namespace std;

class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};

/*
 * @lc app=leetcode.cn id=116 lang=cpp
 *
 * [116] 填充每个节点的下一个右侧节点指针
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:

    // 递归版本, 开始没想到利用next指针
    // Node* connect(Node* root) {
    //     if (!root) return nullptr;
    //     if (root->left) root->left->next = root->right;
    //     if (root->next && root->right && root->next->left) {
    //         root->right->next = root->next->left;
    //     }
    //     connect(root->left); connect(root->right);
    //     return root;
    // }

    Node* connect(Node* root) {
        Node* res = root;
        Node* temp = nullptr;
        while (root) {
            if (root->left) root->left->next = root->right;
            if (root->next && root->right) root->right->next = root->next->left;
            if (!temp) temp = root->left;
            if (root->next) root = root->next; 
            else root = temp, temp = nullptr;
        }
        return res;
    }

};
// @lc code=end

